<?php
namespace Agent\Controller;
class AdminController extends BaseController
{

    //代理用户个人信息管理
    public function index()
    {
        $where['admin_id'] = session(('agent.admin_id'));
        $agent = M('agent');
        $list = $agent->where($where)->find();
        if (empty($list)) {
            $this->error('代理商账号id错误，请前往登录...', U('Login/index', 3));
        }
        $condition['admin_id'] = $list['shangji'];
        $parent_agent_name = $agent->where($condition)->find();
        if (empty($parent_agent_name)) {
            $parent_agent_name = "平台";
        }
        $list['parent_agent_name'] = $parent_agent_name;
        $list['id'] = $list['admin_id'];
        $level = '平台';
        if ($list['dengji'] == 1) {
            $level = '一级';
        } elseif ($list['dengji'] == 2) {
            $level = '二级';
        } elseif ($list['dengji'] == 3) {
            $level = '三级';
        }
        $list['dengji'] = $level;
        $this->assign('list', $list);
        $this->display();
    }

    //修改代理商密码
    public function edit()
    {
        if (IS_POST) {
            $admin_id = I('post.id');
            $admin_password = trim(I('post.admin_password'));
            $repassword = trim(I('post.repassword'));

            if (empty($admin_id)) {
                $this->error('管理员id异常');
            }
            $data = array(
                'admin_id' => $admin_id,
                'admin_password' => md5($admin_password),
            );
            $data = D('Agent')->checkPwdAgent($data);
            if (!$data['state']) {
                $this->error($data['msg'], U('admin/edit', array('id' => $admin_id)));
                exit();
            }
            // 操作成功
            $this->success($data['msg'], U('admin/index'));

        } else {
            $agent_id = trim(I('get.id'));
            if (empty(I('get.id'))) {
                $this->error('代理商账号id错误，请重试...', U('Admin/index', 3));
            }
            $condition['admin_id'] = $agent_id;
            $agent = M('agent');
            $data = $agent->where($condition)->find();
            $this->assign('data', $data);
            $this->display();
        }
    }

    //添加下级代理账号
    public function add_child_agent_account()
    {
        $condition['admin_id'] = session(('agent.admin_id'));
        $agent = M('agent');
        $list = $agent->where($condition)->find();
        if ($list['dengji'] == 3) {
            $this->error('请联系管理员，三级代理商，无法添加下级代理', U('Admin/index'));
        }

        if (IS_POST) {
            $admin_name = trim(I('post.admin_name'));
            $admin_password = trim(I('post.admin_password'));
            $phone = trim(I('post.phone'));
            $email = trim(I('post.email'));
            $status = I('post.status');
            $zhekou = I('post.zhekou');
            $dengji = $list['dengji'] + 1;
            if (empty($admin_name) || !isNames($admin_name, 6, 20)) {
                $this->error('请输入6-20位的账号');
            }
            if (empty($admin_password) || !isPWD($admin_password, 6, 20)) {
                $this->error('请输入6-20位的密码');
            }
            //检查账号是否已存在
            $admin_info = M('Agent')->field('admin_id')->where(array('admin_name' => $admin_name))->find();
            if (!empty($admin_info)) {
                $this->error('账号已存在');
            }
            $data = array(
                'admin_name' => $admin_name,
                'admin_password' => md5($admin_password),
                'phone' => $phone,
                'email' => $email,
                'status' => $status,
                'register_time' => time(),
                'dengji' => $dengji,
                'zhekou' => $zhekou,
                'shangji' => session(('agent.admin_id')),
            );
            $result = D('Agent')->addAgent($data);
            if ($result) {
                $this->success('添加成功', U('admin/agent_list'));
            } else {
                $this->error('添加失败', U('admin/add_child_agent_account'));
            }
        } else {
            $this->display();
        }
    }

    //查看下级代理商列表
    public function agent_list()
    {
        $keyword = trim(I('post.keyword', '', 'htmlspecialchars'));
        //搜索关键词
        if (!empty($keyword)) {
            //设置查询条件，模糊查询
            $map['admin_id|admin_name'] = array('like', "%$keyword%");
        }
        //设置过滤当前代理商id
        $admin_id = session(('agent.admin_id'));
        $map['shangji'] = $admin_id;

        //分页相关
        $agent = M('agent');
        $total = $agent->where($map)->count();
        $pageSize = 10;
        $page = new \Think\Page($total, $pageSize);
        pages($page, $map);
        if ($pageSize < $total) {
            $show = $page->show();
        }
        $data = $agent->where($map)->limit($page->firstRow, $page->listRows)->order('admin_id asc')->select();
        //读取代理商的名称
        $agent_name = $agent->where('admin_id=' . $admin_id)->getField('admin_name');
        foreach ($data as $key => $value) {
            $data[$key]['last_login_time'] = date("Y-m-d H:i", $value['last_login_time']);
            $data[$key]['shangjiname'] = $agent_name;
        }

        $this->assign('agent_id', $admin_id);
        $this->assign('num', $total);
        $this->assign('agent_name', $agent_name);
        $this->assign('keyword', $keyword); //关键词回显
        $this->assign('list', $data);
        $this->assign('show', $show);
        $this->display();
    }

    /**
     * 修改下级指定id的代理商信息
     */
    public function edit_one_agent()
    {
        if (IS_POST) {

            $admin_id = trim(I('post.admin_id'));
            $phone = trim(I('post.phone'));
            $email = trim(I('post.email'));
            $status = trim(I('post.status'));
            if (empty($admin_id)) {
                $this->error('管理员id异常');
            }
            $condition['admin_id'] = $admin_id;
            $data = array(
                'phone' => $phone,
                'email' => $email,
                'status' => $status,
            );

            // 更新运营商折扣率
            $instance = I('post.instance'); //实例
            $system_disk = I('post.system_disk'); //系统盘
            $storage_disc = I('post.storage_disc'); //存储盘
            $network = I('post.network'); //公网带宽
            foreach ($instance as $index => $item) {
                $old_log = M('mid_relation')
                    ->alias('m')
                    ->field('m.*, o.operator_name')
                    ->join('__OPERATOR__ o ON m.operator_id=o.id', 'LEFT')
                    ->where('m.id=' . $index)
                    ->find();

                $data1 = [];
                $data1['id'] = $index;
                $data1['instance'] = $item;
                $data1['system_disk'] = $system_disk[$index];
                $data1['storage_disc'] = $storage_disc[$index];
                $data1['network'] = $network[$index];
                $result = M('mid_relation')->save($data1);

                // 保存相关的折扣率编辑记录
                $depict = sprintf("详情：运营商【%4s】 的
                    实例：%4f --> %f, 
                    系统盘：%4f --> %4f,
                    存储盘：%4f --> %4f,
                    公网带宽：%4f --> %4f",
                    $old_log['operator_name'],
                    $old_log['instance'], $instance[$index],
                    $old_log['system_disk'], $system_disk[$index],
                    $old_log['storage_disc'], $storage_disc[$index],
                    $old_log['network'], $network[$index]);

                $log = [];
                $log['who'] = '代理商';
                $log['target'] = $old_log['operator_name'];
                $log['agent_id'] = $old_log['agent_id'];
                $log['is_agent'] = 1;
                $log['depict'] = $depict;
                $log['time'] = date('Y-m-d H:i:s', time());
                $result = M('rate_update_log')->add($log);
            }
            $res = D('Agent')->editAgent($condition, $data);
            if (!$res['state']) {
                $this->error($res['msg']);
            }
            // 操作成功
            $this->success($res['msg'], U('admin/agent_list'));

        } else {

            $agent_id = I('get.id', 0, 'intval');
            if (empty($agent_id)) {
                $this->error('管理员id异常');
            }
            $where['admin_id'] = $agent_id;
            //管理子级代理商
            $agent_info = M('agent')->where($where)->getField('admin_id,admin_name,dengji,phone,email,status');
            if (empty($agent_info)) {
                $this->error('管理员id异常');
            }

            //查询所有的运营商折扣信息：
            $where = array();
            $where['m.agent_id'] = $agent_id;

            $data = M('mid_relation')
                ->alias('m')
                ->field('m.*, o.operator_name')
                ->join('__OPERATOR__ o ON m.operator_id=o.id', 'LEFT')
                ->order('m.id ASC')
                ->where($where)
                ->select();

            $level = '平台';
            if ($agent_info[$agent_id]['dengji'] == 1) {
                $level = '一级';
            } elseif ($agent_info[$agent_id]['dengji'] == 2) {
                $level = '二级';
            } elseif ($agent_info[$agent_id]['dengji'] == 3) {
                $level = '三级';
            }
            $agent_info[$agent_id]['level'] = $level;
            $this->assign('agent_info', $agent_info[$agent_id]);
            $this->assign('list', $data);
            $this->display();
        }
    }

    /**
     * 修改下级指定id的代理商密码
     */
    public function change_pwd_by_agent_id()
    {
        if (IS_POST) {
            $admin_id = I('post.admin_id');
            $admin_password = trim(I('post.admin_password'));
            $repassword = trim(I('post.repassword'));
            if (empty($admin_password) || !isPWD($admin_password, 6, 20)) {
                $this->error('请输入6-20位的密码');
            }
            if (empty($admin_id)) {
                $this->error('管理员id异常');
            }
            $data = array(
                'admin_id' => $admin_id,
                'admin_password' => md5($admin_password),
                'repassword' => $repassword,
            );
            $data = D('Agent')->editAgentPwd($data);
            if (!$data['state']) {
                $this->error($data['msg']);
                exit();
            }
            // 操作成功
            $this->success($data['msg'], U('admin/index'));
        } else {
            $agent_id = I('get.id', 0, 'intval');
            if (empty($agent_id)) {
                $this->error('管理员id异常');
            }
            $where['admin_id'] = $agent_id;
            $agent_info = M('agent')->where($where)->getField('admin_id,admin_name,phone,dengji');
            if (empty($agent_info)) {
                $this->error('管理员id异常');
            }

            $level = '平台';
            if ([$agent_id]['dengji'] == 1) {
                $level = '一级';
            } elseif ($agent_info[$agent_id]['dengji'] == 2) {
                $level = '二级';
            } elseif ($agent_info[$agent_id]['dengji'] == 3) {
                $level = '三级';
            }
            $agent_info[$agent_id]['level'] = $level;
            $this->assign('agent_info', $agent_info[$agent_id]);
            $this->display();
        }
    }

    public function user_list()
    {
        $keyword = trim(I('post.keyword', '', 'htmlspecialchars'));
        //搜索关键词
        if (!empty($keyword)) {
            //设置查询条件，模糊查询
            $map['id|username'] = array('like', "%$keyword%");
        }
        //设置过滤当前代理商id
        $agent_id = session(('agent.admin_id'));
        $map['agent_id'] = $agent_id;
        $agent = M('agent');
        //分页相关
        $user = M('user');
        $total = $user->where($map)->count();

        $pageSize = 10;
        $page = new \Think\Page($total, $pageSize);
        pages($page, $map);
        if ($pageSize < $total) {
            $show = $page->show();
        }
        $data = $user->where($map)->limit($page->firstRow, $page->listRows)->order('add_agent_time desc')->select();
        //读取代理商的名称
        $agent_name = $agent->where('admin_id=' . $agent_id)->getField('admin_name');

        $this->assign('agent_id', $agent_id);
        $this->assign('num', $total);
        $this->assign('agent_name', $agent_name);
        $this->assign('keyword', $keyword); //关键词回显
        $this->assign('list', $data);
        $this->assign('show', $show);
        $this->display();
    }

    //修改下级会员的折扣率
    public function edit_operator()
    {
        if (IS_POST) {
            $user_id = trim(I('post.uid'));
            // 更新运营商折扣率
            $instance = I('post.instance'); //实例
            $system_disk = I('post.system_disk'); //系统盘
            $storage_disc = I('post.storage_disc'); //存储盘
            $network = I('post.network'); //公网带宽
            foreach ($instance as $index => $item) {
                $data1 = [];
                $data1['id'] = $index;
                $data1['instance'] = $item;
                $data1['system_disk'] = $system_disk[$index];
                $data1['storage_disc'] = $storage_disc[$index];
                $data1['network'] = $network[$index];
                $result = M('mid_relation')->save($data1);

                // 保存相关的折扣率编辑记录
                $old_log = M('mid_relation')
                    ->alias('m')
                    ->field('m.*, o.operator_name')
                    ->join('__OPERATOR__ o ON m.operator_id=o.id', 'LEFT')
                    ->where('m.id=' . $index)
                    ->find();
                $depict = sprintf("详情：运营商【%4s】 的
                    实例：%4f --> %f, 
                    系统盘：%4f --> %4f,
                    存储盘：%4f --> %4f,
                    公网带宽：%4f --> %4f",
                    $old_log['operator_name'],
                    $old_log['instance'], $instance[$index],
                    $old_log['system_disk'], $system_disk[$index],
                    $old_log['storage_disc'], $storage_disc[$index],
                    $old_log['network'], $network[$index]);

                $log = [];
                $log['who'] = '平台';
                $log['target'] = $old_log['operator_name'];
                $log['agent_id'] = $old_log['agent_id'];
                $log['is_agent'] = 0;
                $log['depict'] = $depict;
                $log['time'] = date('Y-m-d H:i:s', time());
                $result = M('rate_update_log')->add($log);
            }
            // 操作成功
            $this->success('修改成功', U('admin/user_list'));

        } else {

            $id = I('get.uid', 0, 'intval');
            if (empty($id)) {
                $this->error('会员id异常');
            }
            $agent_id = I('get.agent_id', 0, 'intval');

            //查询会员信息
            $where['id'] = $id;
            $user_info = M('user')->where($where)->find();
            if (empty($user_info)) {
                $this->error('会员信息不存在');
            }

            //查询所有的运营商折扣信息：
            $where = array();
            $where['m.agent_id'] = $id;
            $where['m.is_agent'] = 0; //查询会员

            $data = M('mid_relation')
                ->alias('m')
                ->field('m.*, o.operator_name')
                ->join('__OPERATOR__ o ON m.operator_id=o.id', 'LEFT')
                ->order('m.id ASC')
                ->where($where)
                ->select();

            $this->assign('user', $user_info);
            $this->assign('list', $data);
            $this->display();
        }
    }

    /**
     * 代理商添加一个下级代理商账号
     */
    public function add_child_agent()
    {
        if (IS_POST) {
            $admin_name = trim(I('post.admin_name'));
            $admin_password = trim(I('post.admin_password'));
            $phone = trim(I('post.phone'));
            $email = trim(I('post.email'));
            $status = I('post.status');
            if (empty($admin_name) || !isNames($admin_name, 6, 20)) {
                $this->error('请输入6-20位的账号');
            }
            if (empty($admin_password) || !isPWD($admin_password, 6, 20)) {
                $this->error('请输入6-20位的密码');
            }
            //检查账号是否已存在
            $admin_info = M('Agent')->field('admin_id')->where(array('admin_name' => $admin_name))->find();
            if (!empty($admin_info)) {
                $this->error('账号已存在');
            }

            //查自身账号
            $where['admin_id'] = session(('agent.admin_id'));
            $agent = M('agent');
            $list = $agent->where($where)->find();
            $dengji = $list['dengji'] + 1;
            $shangji = $where['admin_id'];

            $data = array(
                'admin_name' => $admin_name,
                'admin_password' => md5($admin_password),
                'phone' => $phone,
                'email' => $email,
                'status' => $status,
                'register_time' => time(),
                'dengji' => $dengji,
                'shangji' => $shangji,
            );

            $result = D('Agent')->addAgent($data);

            if ($result) {
                //保存运营商折扣率数据
                $instance = I('post.instance'); //实例
                $system_disk = I('post.system_disk'); //系统盘
                $storage_disc = I('post.storage_disc'); //存储盘
                $network = I('post.network'); //公网带宽
                foreach ($instance as $index => $item) {
                    $data = [];
                    $data['agent_id'] = $result;
                    $data['is_agent'] = 1;
                    $data['operator_id'] = $index;
                    $data['instance'] = $item;
                    $data['system_disk'] = $system_disk[$index];
                    $data['storage_disc'] = $storage_disc[$index];
                    $data['network'] = $network[$index];
                    $result1 = M('mid_relation')->add($data);
                }
                //新添加的代理商 权限组设置
                $group = array(
                    'uid' => $result,
                    'group_id' => 2,  //组权限统一都设置为代理商组的权限
                );
                M('AuthGroupAccess')->add($group);
                $this->success('添加成功', U('admin/agent_list'));
            } else {
                $this->error('添加失败');
            }
        } else {
            $where['admin_id'] = session(('agent.admin_id'));
            $agent_info = M('agent')->where($where)->find();
            $level = '二级';
            if ($agent_info['dengji'] == 1) {
                $level = '二级';
            } elseif ($agent_info['dengji'] == 2) {
                $level = '三级';
            } elseif ($agent_info['dengji'] == 3) {
                $this->error('错误，三级代理商不能添加下级代理商', U('admin/agent_list'));
            }
            $agent_info['level'] = $level;
            //查询所有的运营商折扣信息：
            $data = M('operator')->getField('id, operator_name, cate');
            $this->assign('agent_info', $agent_info);
            $this->assign('list', $data);
            $this->display();
        }
    }

    //获取折扣率修改记录（指定代理商id的 ）
    public function get_rate_update_log()
    {
        $agent_id = I('get.id', 0, 'intval');
        $is_agent = I('get.is_agent', 0, 'intval');
        if ($is_agent) {
            //代理商
            $agent_info = M('agent')->where('admin_id=' . $agent_id)->find();
            $level = '平台';
            if ($agent_info['dengji'] == 1) {
                $level = '一级';
            } elseif ($agent_info['dengji'] == 2) {
                $level = '二级';
            } elseif ($agent_info['dengji'] == 3) {
                $level = '三级';
            }
            $title = $level . "代理商";
        } else {
            //会员
            $agent_info = M('user')->where('id=' . $agent_id)->find();
            $title = "会员【" . $agent_info['truename'] . "】";
        }

        $keyword = trim(I('keyword'));
        //搜索关键词
        if (!empty($keyword)) {
            //设置查询条件,模糊查询
            $map['target'] = array('like', "%$keyword%");
        }

        $rate_update_log = M('rate_update_log');
        $map['agent_id'] = $agent_id;
        $map['is_agent'] = $is_agent;
        $total = $rate_update_log->where($map)->count();

        $pageSize = 10;
        $page = new \Think\Page($total, $pageSize);
        pages($page, $map);
        if ($pageSize < $total) {
            $show = $page->show();
        }
        $log_list = $rate_update_log->where($map)->limit($page->firstRow, $page->listRows)->order('time desc')->select();

        $this->assign('keyword', $keyword);
        $this->assign('title', $title);
        $this->assign('list', $log_list);
        $this->assign('show', $show);//分页

        $this->display();
    }
}